package com.flea.web.controller;

import com.flea.model.Product;
import com.flea.service.ISearchService;
import com.flea.service.ProductService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author hc24
 * @date 2021.1.21 15:58
 */
@Controller
public class ProductController {

    @Resource
    private ProductService productService;

    @Resource(name = "fullTextSearch")
    private ISearchService searchService;


    @GetMapping("/products")
    public ModelAndView search(HttpSession session, String key,
                               @RequestParam(name = "pager.offset", defaultValue = "0") int offset,
                               @RequestParam(name = "pager.pageSize", defaultValue = "10") int pageSize) {
        System.out.println(session.getId());

        PageRequest pageRequest = PageRequest.of(offset / pageSize, pageSize);

        Page<Product> productPage = searchService.searchProducts(key, pageRequest);


        ModelAndView mav = new ModelAndView("search_result");
        mav.addObject("productPage", productPage);
        mav.addObject("key", key);

        return mav;
    }

    @GetMapping("/products/latest")
    public ModelAndView latest(@RequestParam(name = "pager.offset", defaultValue = "0") int offset,
                               @RequestParam(name = "pager.pageSize", defaultValue = "10") int pageSize) {
        PageRequest pageRequest = PageRequest.of(offset / pageSize, pageSize);
        Page<Product> productPage = productService.findLatest(pageRequest);

        ModelAndView mav = new ModelAndView("search_result");
        mav.addObject("productPage", productPage);

        return mav;
    }
}
